<template>
  <el-dialog
    v-model="visible"
    :title="`资产详情 - ${detailData?.original_data?.filename || '加载中...'}`"
    width="1200px"
    :close-on-click-modal="false"
    top="5vh"
  >
    <div v-loading="loading" class="detail-content" v-if="detailData">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-heading">📌 基本信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="临时ID">
            {{ detailData.temp_id || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="搜索ID">
            {{ detailData.search_id || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="关键词">
            {{ detailData.keyword || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="任务ID">
            {{ detailData.task_id || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="任务名称">
            {{ detailData.task_name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(detailData.status)" size="small">
              {{ getStatusText(detailData.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 文件信息 -->
      <div class="detail-section">
        <h3 class="section-heading">📄 文件信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="文件名">
            {{ detailData.original_data?.filename || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            <span v-if="detailData.original_data?.size_human">
              {{ detailData.original_data.size_human }}
            </span>
            <span v-else-if="detailData.original_data?.size">
              {{ formatSize(detailData.original_data.size) }}
            </span>
            <span v-else>-</span>
            <span
              v-if="detailData.original_data?.size"
              class="size-bytes"
              style="margin-left: 8px; color: #909399"
            >
              ({{ formatNumber(detailData.original_data.size) }} 字节)
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <span v-if="detailData.original_data?.ext">
              .{{ detailData.original_data.ext }}
            </span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="文件ID">
            {{ detailData.original_data?.id || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="用户">
            {{ detailData.original_data?.user || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ detailData.original_data?.updatetime || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="分享链接" :span="3">
            <el-link
              v-if="detailData.original_data?.url"
              :href="detailData.original_data.url"
              target="_blank"
              type="primary"
            >
              {{ detailData.original_data.url }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 风险评估 -->
      <div class="detail-section">
        <h3 class="section-heading">⚠️ 风险评估</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="风险评分">
            <el-tag
              :type="getRiskTagType(detailData.risk_assessment?.risk_score)"
              size="small"
            >
              {{ detailData.risk_assessment?.risk_score || 0 }} 分
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="风险等级">
            <el-tag
              :type="getRiskLevelTag(detailData.risk_assessment?.risk_level)"
              size="small"
            >
              {{ getRiskLevelText(detailData.risk_assessment?.risk_level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="置信度">
            {{
              detailData.risk_assessment?.confidence
                ? `${(detailData.risk_assessment.confidence * 100).toFixed(1)}%`
                : "-"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="风险因素" :span="3">
            <div
              v-if="
                detailData.risk_assessment?.risk_factors &&
                detailData.risk_assessment.risk_factors.length > 0
              "
            >
              <el-tag
                v-for="(factor, index) in detailData.risk_assessment.risk_factors"
                :key="index"
                type="warning"
                size="small"
                style="margin-right: 8px; margin-bottom: 4px"
              >
                {{ factor }}
              </el-tag>
            </div>
            <span v-else class="no-data">-</span>
          </el-descriptions-item>
          <el-descriptions-item
            label="匹配规则"
            :span="3"
            v-if="
              detailData.risk_assessment?.matched_rules &&
              detailData.risk_assessment.matched_rules.length > 0
            "
          >
            <el-table
              :data="detailData.risk_assessment.matched_rules"
              border
              size="small"
            >
              <el-table-column prop="rule_id" label="规则ID" width="150" />
              <el-table-column prop="rule_name" label="规则名称" />
              <el-table-column prop="weight" label="权重" width="100">
                <template #default="{ row }">
                  {{ (row.weight * 100).toFixed(1) }}%
                </template>
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 缓存信息 -->
      <div class="detail-section">
        <h3 class="section-heading">💾 缓存信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="缓存时间">
            {{ detailData.cached_at || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="过期时间">
            {{ detailData.expires_at || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="剩余TTL">
            <span v-if="detailData.ttl">
              {{ formatTTL(detailData.ttl) }}
            </span>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 元数据信息 -->
      <div class="detail-section" v-if="detailData.metadata">
        <h3 class="section-heading">🔧 元数据信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="来源">
            {{ detailData.metadata.source || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="扫描类型">
            {{ detailData.metadata.scan_type || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ detailData.metadata.created_by || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { getCacheAssetDetail } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  tempId: { type: String, default: null },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const loading = ref(false);
const detailData = ref<any>(null);

// 监听弹窗打开，获取详情
watch(
  () => props.modelValue,
  (val) => {
    if (val && props.tempId) {
      fetchDetail();
    } else {
      detailData.value = null;
    }
  }
);

// 获取详情
const fetchDetail = async () => {
  if (!props.tempId) return;

  loading.value = true;
  try {
    const result = await getCacheAssetDetail(props.tempId);
    if (result.code === 200 && result.data) {
      detailData.value = result.data;
    } else {
      detailData.value = null;
    }
  } catch (error: any) {
    console.error("获取资产详情失败:", error);
    detailData.value = null;
  } finally {
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (
  status?: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "warning",
    confirmed: "success",
    ignored: "info",
  };
  return typeMap[status || ""] || "info";
};

// 获取状态文本
const getStatusText = (status?: string): string => {
  const textMap: Record<string, string> = {
    pending: "待处理",
    confirmed: "已确认",
    ignored: "已忽略",
  };
  return textMap[status || ""] || status || "未知";
};

// 获取风险评分标签类型
const getRiskTagType = (
  score?: number
): "success" | "warning" | "danger" | "info" => {
  if (!score) return "info";
  if (score >= 80) return "danger";
  if (score >= 60) return "warning";
  return "info";
};

// 获取风险等级标签类型
const getRiskLevelTag = (
  level?: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    high: "danger",
    medium: "warning",
    low: "info",
  };
  return typeMap[level || ""] || "info";
};

// 获取风险等级文本
const getRiskLevelText = (level?: string): string => {
  const textMap: Record<string, string> = {
    high: "高风险",
    medium: "中风险",
    low: "低风险",
  };
  return textMap[level || ""] || "未知";
};

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i];
};

// 格式化数字（添加千分位）
const formatNumber = (num: number): string => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 格式化TTL（秒转可读格式）
const formatTTL = (seconds?: number): string => {
  if (!seconds || seconds === 0) return "无";
  if (seconds < 60) return `${seconds}秒`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`;
  return `${Math.floor(seconds / 86400)}天`;
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.detail-content {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-heading {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.no-data {
  color: #909399;
  font-size: 14px;
}
</style>

